import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../services/api_service.dart';
import '../utils/logger.dart';
import '../utils/compress_utils.dart';
import 'rich_text_display.dart';

/// 简化版富文本编辑器
/// 支持文本编辑和图片插入，解决图片显示问题
class SimpleRichTextEditor extends StatefulWidget {
  final String? initialContent;
  final String hintText;
  final Function(String content)? onContentChanged;
  final bool enabled;
  final TextEditingController? controller;
  final double? minHeight;

  const SimpleRichTextEditor({
    super.key,
    this.initialContent,
    this.hintText = '请输入内容...',
    this.onContentChanged,
    this.enabled = true,
    this.controller,
    this.minHeight = 200,
  });

  @override
  State<SimpleRichTextEditor> createState() => _SimpleRichTextEditorState();
}

class _SimpleRichTextEditorState extends State<SimpleRichTextEditor> {
  late final TextEditingController _controller;
  final FocusNode _focusNode = FocusNode();
  bool _isUploading = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? TextEditingController();
    if (widget.initialContent != null) {
      _controller.text = widget.initialContent!;
    }
    _controller.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _controller.dispose();
    }
    _focusNode.dispose();
    super.dispose();
  }

  void _onTextChanged() {
    widget.onContentChanged?.call(_controller.text);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          // 工具栏
          _buildToolbar(),
          
          // 编辑区域
          _buildEditor(),
        ],
      ),
    );
  }

  /// 构建工具栏
  Widget _buildToolbar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        border: Border(
          bottom: BorderSide(color: Colors.grey[300]!),
        ),
      ),
      child: Row(
        children: [
          // 插入图片按钮
          _buildToolButton(
            icon: Icons.image,
            label: '图片',
            onTap: _insertImage,
            isLoading: _isUploading,
          ),
          
          const SizedBox(width: 12),
          
          // 预览按钮
          _buildToolButton(
            icon: Icons.preview,
            label: '预览',
            onTap: _previewContent,
          ),
          
          const Spacer(),
          
          // 字数统计
          Text(
            '${_controller.text.length} 字',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建工具按钮
  Widget _buildToolButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
    bool isLoading = false,
  }) {
    return GestureDetector(
      onTap: isLoading ? null : onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(color: Colors.grey[300]!),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            isLoading
                ? SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                    ),
                  )
                : Icon(icon, size: 16, color: Colors.grey[700]),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[700],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建编辑区域
  Widget _buildEditor() {
    return Container(
      constraints: BoxConstraints(minHeight: widget.minHeight ?? 200),
      padding: const EdgeInsets.all(16),
      child: TextField(
        controller: _controller,
        focusNode: _focusNode,
        enabled: widget.enabled,
        maxLines: null,
        decoration: InputDecoration(
          hintText: widget.hintText,
          border: InputBorder.none,
          hintStyle: TextStyle(
            color: Colors.grey[400],
            fontSize: 16,
          ),
        ),
        style: const TextStyle(
          fontSize: 16,
          height: 1.5,
        ),
      ),
    );
  }

  /// 插入图片
  void _insertImage() {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              '插入图片',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                  child: _buildImageSourceOption(
                    icon: Icons.photo_library,
                    title: '相册选择',
                    onTap: () {
                      Navigator.pop(context);
                      _selectImageFromGallery();
                    },
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: _buildImageSourceOption(
                    icon: Icons.camera_alt,
                    title: '拍照',
                    onTap: () {
                      Navigator.pop(context);
                      _takePhoto();
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  /// 构建图片来源选项
  Widget _buildImageSourceOption({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey[200]!),
        ),
        child: Column(
          children: [
            Icon(icon, size: 32, color: Colors.blue[600]),
            const SizedBox(height: 8),
            Text(
              title,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 从相册选择图片
  Future<void> _selectImageFromGallery() async {
    try {
      final picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      
      if (image != null) {
        await _handleImageSelected(File(image.path));
      }
    } catch (e) {
      _showErrorSnackBar('选择图片失败: $e');
    }
  }

  /// 拍照
  Future<void> _takePhoto() async {
    try {
      final picker = ImagePicker();
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      
      if (photo != null) {
        await _handleImageSelected(File(photo.path));
      }
    } catch (e) {
      _showErrorSnackBar('拍照失败: $e');
    }
  }

  /// 处理选择的图片
  Future<void> _handleImageSelected(File imageFile) async {
    setState(() {
      _isUploading = true;
    });

    try {
      // 先压缩图片
      final compressedFile = await CompressUtils.compressContentImage(imageFile);
      if (compressedFile == null) {
        _showErrorSnackBar('图片压缩失败');
        return;
      }

      final result = await ApiService().uploadPostImage(compressedFile);
      
      if (result['code'] == 200 || result['code'] == 0) {
        final imageUrl = result['data'];
        
        // 使用新的图片标记格式
        _insertTextAtCursor('\n[IMAGE:${imageUrl}]\n');
        
        _showSuccessSnackBar('图片上传成功');
      } else {
        _showErrorSnackBar(result['message'] ?? '图片上传失败');
      }
    } catch (e) {
      Logger.e('SIMPLE_RICH_TEXT_EDITOR', '图片上传失败: $e');
      _showErrorSnackBar('图片上传失败: $e');
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  }

  /// 在光标位置插入文本
  void _insertTextAtCursor(String text) {
    final currentText = _controller.text;
    final selection = _controller.selection;
    final newText = currentText.replaceRange(
      selection.start,
      selection.end,
      text,
    );
    _controller.text = newText;
    _controller.selection = TextSelection.collapsed(
      offset: selection.start + text.length,
    );
  }

  /// 预览内容
  void _previewContent() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('内容预览'),
        content: SizedBox(
          width: double.maxFinite,
          height: 400,
          child: SingleChildScrollView(
            child: _controller.text.isEmpty 
                ? const Text('暂无内容')
                : SimpleRichTextDisplay(
                    content: _controller.text,
                    textStyle: const TextStyle(
                      fontSize: 14,
                      height: 1.5,
                    ),
                  ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }

  /// 获取编辑器内容
  String get content => _controller.text;

  /// 设置编辑器内容
  set content(String value) {
    _controller.text = value;
  }
}

/// 简化版富文本编辑器控制器
class SimpleRichTextEditorController extends TextEditingController {
  String get content => text;
  set content(String value) => text = value;
}
